package com.zhm.demo.utils;

import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.github.benmanes.caffeine.cache.RemovalCause;
import com.github.benmanes.caffeine.cache.RemovalListener;
import lombok.extern.slf4j.Slf4j;
import org.checkerframework.checker.nullness.qual.Nullable;

import java.util.concurrent.TimeUnit;

@Slf4j
public class CaffeineTest {

    public static Cache<String, Object> initCache (){
        Cache<String, Object> cache = Caffeine.newBuilder()
                // 设置最后一次写入或访问后经过固定时间过期
                .expireAfterWrite(60, TimeUnit.SECONDS)
                // 初始的缓存空间大小
                .initialCapacity(100)
                // 缓存的最大条数
                .maximumSize(1000)
                .evictionListener(new RemovalListener<String, Object>() {
                    @Override
                    public void onRemoval(@Nullable String k, @Nullable Object v, RemovalCause removalCause) {
                        log.info("{} {} {}", k, v, removalCause);
                    }
                })
                .build();

        return cache;
    }
    public static void main(String[] args) {

        Cache<String, Object> cache = initCache();
        cache.put("a", "");
        Object a = cache.getIfPresent("a");
        System.out.println(a);
        Object b = cache.get("b", (k) -> {
            return k + "b";
        });
        System.out.println(b);
    }
}
